import cv2 as cv

# 读入左右反向图片
imgL = cv.imread(r'LENA.jpg')
imgR = cv.imread(r'LENA.jpg')
# 灰度图转换
grayL = cv.cvtColor(imgL, cv.COLOR_BGR2GRAY)
grayR = cv.cvtColor(imgR, cv.COLOR_BGR2GRAY)
# 创建orb算子以及提取描述子
orb = cv.ORB_create()
kpL, dstL = orb.detectAndCompute(grayL, None)
kpR, dstR = orb.detectAndCompute(grayR, None)
# 创建FBMatcher类对象，并且进行匹配
BF = cv.BFMatcher(cv.NORM_L2)
matches = BF.match(dstL, dstR)
# 显示orb匹配结果
img1 = cv.drawMatches(imgL, kpL, imgR, kpR, matches, None, flags=2)
cv.imshow("ORB", img1)
#--------------------------------------#
# 初始化Bruteforce匹配器
bf = cv.BFMatcher()
# 通过KNN匹配两张图片的描述子
matches = bf.knnMatch(dstL, dstR, k=2)
# 筛选比较好的匹配点
good = []
for i, (m, n) in enumerate(matches):
    if m.distance < 0.8 * n.distance:
        good.append(m)
# 画出匹配点
img2 = cv.drawMatches(imgL, kpL, imgR, kpR, good, None, flags=2)
cv.imshow("ORB-BF", img2)

cv.waitKey(0)
cv.destroyAllWindows()
